package cn.edu.whu.forecast.util;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.List;
/**
* 有关CSV文件生成的工具类
* @author fullangleblank
* @since 2022/6/24
*/
public class CSVFileUtil {

    /**
     * 创建csv文件
     *
     * @param heads    数据图头
     * @param dataList 数据列表
     * @param fileName 文件名称
     * @param filePath 文件路径
     */
    public static void createCSV(List<List<Object>> heads, List<List<Object>> dataList, String fileName, String filePath,Boolean append) {

        //数据
        File csvFile;
        BufferedWriter csvWriter = null;
        try {
            csvFile = new File(filePath + fileName);
            File parent = csvFile.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            csvFile.createNewFile();

            // GB2312使正确读取分隔符","
            csvWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(csvFile,append), StandardCharsets.UTF_8), 1024);

            //文件下载，使用如下代码
//            response.setContentType("application/csv;charset=gb18030");
//            response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
//            ServletOutputStream out = response.getOutputStream();
//            csvWriter = new BufferedWriter(new OutputStreamWriter(out, "GB2312"), 1024);

            int num = heads.get(0).size() / 2;
            StringBuilder buffer = new StringBuilder();
            for (int i = 0; i < num; i++) {
                buffer.append(" ,");
            }
//
            // 写入文件头部
            //for(List<Object> head : heads) writeRow(head, csvWriter);

            // 写入文件内容
            for (List<Object> row : dataList) writeRow(row, csvWriter);

            csvWriter.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert csvWriter != null;
                csvWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 写一行数据
     * @throws IOException ioexception
     */
    private static void writeRow(List<Object> row, BufferedWriter csvWriter) throws IOException {
        for (Object data : row) {
            String rowStr = "" + data + ",";
            csvWriter.write(rowStr);
        }
        csvWriter.newLine();
    }
}
